package com.letoken.platform.admin.service.impl;

import com.letoken.platform.admin.service.CaptchaService;
import com.letoken.platform.admin.util.BracePlaceholder;
import com.letoken.platform.pub.enums.ApiResponseEnum;
import com.letoken.platform.pub.enums.LetokenApiResponseEnum;
import com.letoken.platform.pub.exception.ApiServiceException;
import com.letoken.platform.repo.admin.captcha.ArithmeticCaptcha;
import com.letoken.platform.repo.admin.captcha.CaptchaBuilder;
import com.letoken.platform.repo.admin.redis.AdminUserInfoRedis;
import com.letoken.platform.repo.admin.res.user.CaptchaRes;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author xiehui
 * @version 1.0
 * @date 2023-06-27 15:03
 */
@Service
@Log4j2
public class CaptchaServiceImpl implements CaptchaService {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 生成uuid，并去除横线
     * @return uuid
     */
    public static String generateUUID() {
        return UUID.randomUUID().toString().replace("-","");
    }

    /**
     * token过期时间
     */
    Integer SESSION_EXPIRE_TIME = 120;

    /**
     * 验证码过期时间
     */
    Integer CAPTCHA_EXPIRE_TIME = 3;


    String CAPTCHA_KEY = "captcha:{uuid}";



    @Override
    public CaptchaRes generateCaptcha() {
        ArithmeticCaptcha ac = CaptchaBuilder.<ArithmeticCaptcha>newArithmeticBuilder().len(3).build();
        String text = ac.text();
        String uuid = generateUUID();
        String key = BracePlaceholder.resolve(CAPTCHA_KEY, uuid);

        TimeUnit time = TimeUnit.MINUTES;
       redisTemplate.opsForValue().set(key, text, CAPTCHA_EXPIRE_TIME, TimeUnit.MINUTES);

        return new CaptchaRes(uuid, ac.toBase64());
    }

    @Override
    public boolean checkCaptcha(String uuid, String captcha) {
        Boolean flag = true;
        String key = BracePlaceholder.resolve(CAPTCHA_KEY, uuid);
        String text = (String) redisTemplate.opsForValue().get(key);
        if (ObjectUtils.isEmpty(text)){
            flag = false;
            throw new ApiServiceException(ApiResponseEnum.ERROR_009);
        }
        if (!captcha.equalsIgnoreCase(text)) {
            flag = false;
            throw new ApiServiceException(ApiResponseEnum.ERROR_010);
        }
        redisTemplate.delete(key);
        return flag;
    }
}
